<template>
  <el-container id="databaseContainer" v-if="isRouterAlive">
    <el-aside>
      <el-row class="tac">
        <el-col :span="24">
          <h3 class="aside-title">组织架构</h3>
          <el-tree highlight-current
                   :props="defaultProps"
                   @node-collapse="handleNodeCollapse"
                   :load="loadNode"
                   node-key="id"
                   :default-expanded-keys="expandKey"
                   @node-click="handleNodeClick"
                   lazy>
          </el-tree>
        </el-col>
      </el-row>
    </el-aside>
    <el-main v-show="!ifsearch">
      <el-header>
        <el-row>
            <el-button class="go-back" @click="handleGoBack">
                <i class="el-icon-arrow-left"></i>
                上一级
            </el-button>
            <el-breadcrumb separator-class="el-icon-arrow-right" class="tit">
              <el-breadcrumb-item  ><i @click="clickDatabase" :class="isout == -1 ? 'current':''">资料库</i></el-breadcrumb-item>
                  <template v-for="(item,index) in checkedFilePath">
                    <el-breadcrumb-item :key='index'><i @click="upperFile(item,index)" :class="isout == index ? 'current':''">{{item.fileName}}</i></el-breadcrumb-item>
                  </template>
          </el-breadcrumb>
        </el-row>
        <el-row>
          <el-button-group>
              <el-button
                      plain
                      @click="listVisibleFun(0)"
                      :class="listVisible ? 'focus' : ''">
                  <i class="fa fa-bars"></i>
              </el-button>
              <el-button
                      plain
                      @click="listVisibleFun(1)"
                      :class="!listVisible? 'focus' : ''"
                      icon="el-icon-menu">
              </el-button>
          </el-button-group>
          <el-button class="refresh" icon="el-icon-refresh" @click="reloadFolders"></el-button>
        </el-row>
      </el-header>
      <div class="toolbar">
        <el-col :span="12">
          共<span class="count">{{records}}</span>份资料
        </el-col>
        <!--<el-col :span="12">-->
          <!--<el-input class="search-box"-->
                    <!--placeholder="在当前目录搜索"-->
                    <!--v-model="searchVal" size="small" @keyup.enter.native="submitSearch">-->
            <!--<i slot="prefix" class="el-input__icon el-icon-search"></i>-->
          <!--</el-input>-->
        <!--</el-col>-->
      </div>
      <!--数据-->
      <database-details v-if="isDatabaseData"
                        :databaseData="databaseData"
                        :currentPage="currentPage"
                        :pageSize="pageSize"
                        v-on:fileTotal="fileTotal"
                        v-on:checkFilePath="checkFilePath"
                        :records="records"
                        @handleCurrentChange="handleCurrentChange"
                        @handleSizeChange="handleSizeChange"
                        ref="details"
                        :listVisible="listVisible">
      </database-details>
    </el-main>
    <search-list class="searchList"
                 @downloadFile="downloadFile"
                 :searchInput="searchInput"
                 ref="search"
                 @handleCellClick="handleCellClick"
                 v-show="ifsearch"></search-list>
  </el-container>
</template>

<script>
  import { mapState ,mapMutations} from "vuex";
  import DatabaseDetails from './DatabaseDetails.vue'
  import SearchList from "./SearchList";

  export default {
    data() {
      return {
        isRouterAlive: true,
        expandKey:[localStorage.getItem('companyId')],
        companyName: localStorage.getItem('companyName'),
        companyId: localStorage.getItem('companyId'),
        listVisible: true,
        dataFile: [
          {
            id: localStorage.getItem('companyId'),
            label: localStorage.getItem('companyName'),
            children: [],
            leaf: false
          }
        ],
        defaultProps: {
          children: 'children',
          label: 'label',
          isLeaf: 'leaf'
        },
        databaseData: [],
        currentPage:1,
        pageSize:10,
        records:0,
        isDatabaseData: true,
        searchVal:'',
        checkedFilePath:[],
        departmentId:0,
        positionId:0,
        isout:-1,
        ifsearch:false,
      };
    },
    components: {SearchList, DatabaseDetails},
    mounted() {
      this.setSearchInput("");
      this.$refs.search.companyId = this.companyId;
      this.$store.state.canSearch = false;
      this.$store.state.placeHolder = "搜索资料库"
      this.getCompanyFile(this.companyId,this.departmentId,this.positionId)
    },
    computed: {
      ...mapState([ "searchInput"])
    },
    watch: {
      dataFile: function (newVal, oldVal) {
        if (newVal == oldVal) {
          return this.dataFile
        }
      },
      searchInput:{
        handler: function (newVal, oldVal) {
          if(newVal != oldVal){
            console.log("this is searchInput new data ", newVal);
            this.$refs.search.inputdata = newVal;
            if(newVal.length==0){
              this.ifsearch=false;
              return;
            }
            this.ifsearch=true;
            this.$refs.search.searchBigData();
            // if(this.checkedFilePath.length == 0){
            //
            // }else{
            //   this.$refs.search.searchBigData();
            // }
          }
        }
      },
    },
    methods: {
      ...mapMutations(["setSearchInput"]),
      downloadFile(file){
        this.$refs.details.downloadFile(file);
      },
      reloadFolders() {
        this.isRouterAlive = false
        this.$nextTick(function () {
          this.isRouterAlive = true
        })
      },
      handleCellClick(item,isword){
        console.log(item,isword);
        this.checkedFilePath = [];
        this.ifsearch = false;
        //如果点击的是路径
        if(isword == true){
          console.log("isword");
          item.pathArray.forEach((val,key)=>{
            this.checkedFilePath.push({
              fileType:1,
              fileName:val.name,
              id:val.id.split(".")[0]
            })
          })
          this.checkFilePath(this.checkedFilePath);
          this.$refs.details.handleCellClick
          (this.checkedFilePath[this.checkedFilePath.length-1],"a");
        }else{
          //如果点击的是文件夹
          if(item.fileType == 1){
            this.$refs.details.filePath.pop();
            item.pathArray.forEach((val,key)=>{
              this.checkedFilePath.push({
                fileType:1,
                fileName:val.name,
                id:val.id.split(".")[0],
                dirId:val.id.split(".")[1]
              })
              this.$refs.details.filePath.push({
                fileType:1,
                fileName:val.name,
                id:val.id.split(".")[0],
                dirId:val.id.split(".")[1]
              })
            })
            this.$refs.details.handleCellClick(item);
          }else{
            //如果点击的是文件
            item.pathArray.forEach((val,key)=>{
              this.checkedFilePath.push({
                fileType:0,
                fileName:val.name,
                id:val.id.split(".")[0]
              })
            })
            this.$refs.details.handleCellClick
            (this.checkedFilePath[this.checkedFilePath.length-1],undefined,item);
          }
        }

      },
      clickDatabase(){
        this.$store.state.placeHolder = "搜索资料库"
        this.isout = -1;
        this.getCompanyFile(this.companyId,this.departmentId,this.positionId);
        this.checkedFilePath = [];
      },
      handleGoBack(){
        console.log(this.checkedFilePath);
        this.checkedFilePath.pop();
        if(this.checkedFilePath.length == 0){
          this.$store.state.placeHolder = "搜索资料库"
          this.isout = -1;
          this.$refs.search.fileId = 0;
          this.getCompanyFile(this.companyId,this.departmentId,this.positionId);

        }else{
          this.isout = this.checkedFilePath.length-1;
          this.$refs.details.handleCellClick(this.checkedFilePath[this.checkedFilePath.length-1],"a");
        }
      },
      handleSizeChange(data){
        this.pageSize = data;
        this.getCompanyFile(this.companyId,this.departmentId,this.positionId)
      },
      handleCurrentChange(data){
        this.currentPage = data;
        this.getCompanyFile(this.companyId,this.departmentId,this.positionId)
      },
      //搜索
      async submitSearch(){
        let para={
          fileName:this.searchVal,
          dirId:0
        }
        let res = this.$http.post('/file/getfileLike',para)
        console.log('搜索结果：',res)
      },
      //子组件获得文件数
      fileTotal(data){
        console.log(data);
        this.records = data
      },
      //子组件传的获取当前文件路径
      checkFilePath(data){
        console.log(data);
        this.$refs.details.filePath = data;
        if(data.length>0){
          this.$refs.search.fileId = data[0].id;
        }else{
          this.$refs.search.fileId = 0;
        }
        this.isout = data.length-1;
        this.checkedFilePath = data;
        console.log(this.checkedFilePath);
      },
      //返回到指定路径
      upperFile(item,index){
        this.isout = index;
        console.log(item)
        this.$refs.search.fileId = item.id;
        let checkFileItem = item;
        let index2 = this.checkedFilePath.indexOf(checkFileItem);
        this.checkedFilePath.splice(index2+1);
        this.$refs.details.handleCellClick(this.checkedFilePath[this.checkedFilePath.length-1],"a");
      },
      //节点被点击时触发
      handleNodeClick(data,node,comp){
        this.ifsearch = false;
        console.log('被点击时的node label:',node)
        if(node.level == 1){
          this.$refs.search.companyId = this.companyId;
        }else if(node.level == 2){
          this.$refs.search.departmentId = this.departmentId;
        }else if(node.level == 3){
          this.$refs.search.positionId = node.data.id;
          console.log(node);
          this.getCompanyFile(node.data.companyId,node.data.departmentId,node.data.id);//带参数调用
        }
      },
      //节点被关闭时触发
      handleNodeCollapse(data, node, comp) {
        // console.log('handleNodeCollapse==', data);
        node.loaded = false
        node.childNodes = []
        data.children = []
      },
      //公司级别用户资料库
      async getCompanyFile(companyId,departmentId,positionId){
        let para = {
          companyId: companyId,
          departmentId:departmentId,
          positionId:positionId,
          page: this.currentPage,
          rows: this.pageSize
        }
        let res = await this.$http.post('/company/getFile', para)
        // console.log('根目录资料库：',res)
        if (res.status == 200 && res.data.records != null){
          console.log("根目录资料库",res.data)
          this.isDatabaseData = false
          this.$nextTick(function () {
            this.isDatabaseData = true
          })
          this.databaseData=res.data.records;
          console.log(this.databaseData);
          this.records = res.data.total
        }
      },
      async loadNode(node, resolve) {
        if (node.level === 0) {
          // console.log(this.dataFile);
          return resolve(this.dataFile);
        }
        console.log(node);
        let folders = []
        if (node.level == 1 || node.data.label == undefined) {
          this.dataFile[0].children = []
          let fileList = await this.$http.get('/department/list?companyId=' + this.companyId)
          if (fileList.status === 200 && fileList.data !== null) {
            // console.log(fileList)
            // console.log(this.dataFile);
            fileList.data.forEach((val) => {
              folders.push({
                companyId: val.companyId,
                label: val.departmentName,
                id: val.id,
                children: [],
              })
            })
          }
          this.$refs.search.companyId = this.companyId;
          this.getCompanyFile(this.companyId,0,0);//带参数调用
        } else if(node.level == 2){
          console.log(node);
          let fileList = await this.$http.get('/position/getupDep?departmentId=' + node.data.id)
          if (fileList.status === 200 && fileList.data !== null) {
            // console.log(fileList)
            // console.log(this.dataFile[0].children);
            fileList.data.forEach((val) => {
              folders.push({
                companyId: node.data.companyId,
                departmentId: val.departmentId,
                label: val.positionName,
                id: val.id,
                children: [],
              })
            })
            this.companyId = node.data.companyId
            this.departmentId = node.data.id;
            this.positionId = 0;
            this.$refs.search.departmentId = this.departmentId;
            this.getCompanyFile(node.data.companyId,node.data.id,0);//带参数调用
          }
        }else if(node.level == 3){
          console.log(node);
          this.companyId = node.data.companyId;
          this.departmentId = node.data.departmentId;
          this.positionId = node.data.id;
          this.$refs.search.positionId = this.positionId;
          this.getCompanyFile(node.data.companyId,node.data.departmentId,node.data.id);//带参数调用
        }
        return resolve(folders);
      },
      listVisibleFun(e) {
        if (e === 0) {
          this.listVisible = true;
        } else {
          this.listVisible = false;
        }
      },
    }
  };
</script>
<style lang="scss">
    #databaseContainer{
        .el-menu-item-group__title {
            padding: 0;
        }

        .el-menu-item {
            height: 40px;
            line-height: 40px;
        }

        .is-active {
            color: #666666 !important;
        }

        .el-submenu__title {
            height: 40px;
            line-height: 40px;
        }
    }
</style>
<style lang="scss" scoped>
  @import "scss_vars";

  #databaseContainer {
    position: absolute;
    margin-left: 120px;
    top: 80px;
    left: 0;
    right: 0;
    bottom: 0;
    overflow: hidden;
    .searchList {
      width: 100%;
      height: 100%;
        background: white;
    }

    .el-aside {
      flex: 0 0 200px;
      height: 100%;
      width: 200px !important;
      background: $main-bg;
      overflow-y: auto;
      overflow-x: auto;
      border-right: 1px solid $black-bg;

      .tac {
        height: 100%;

        .aside-title {
          font-size: 15px;
          font-weight: 400;
          color: rgba(84, 157, 232, 1);
          padding: 15px 10px 20px 20px;
        }

        .el-col {
          height: 100%;
          .el-menu {
            border: 0 !important;

            .el-submenu {
              img {
                margin-right: 7px;
              }
            }
            .active {
              color: #549de8;
            }
          }
        }
      }
    }
    .el-main {
      flex: 1;
      overflow-y: scroll;
      background: white;
      padding: 0;

      .el-header {
        padding: 8px 20px;
        height: 54px !important;
        line-height: 30px;
        background: $main-bg;
        border-bottom: 1px solid $black-bg;
        display: flex;
        justify-content: space-between;
        align-items: center;
          .el-row{
              display: flex;
              align-items: center;
          }
          .refresh{
              display: flex;
              justify-content: center;
              align-items: center;
              width: 42px;
              height: 36px;
          }
          .el-button-group{
              margin-right: 10px;
              .el-button{
                  padding:10px;
                  width: 42px!important;
              }
              .focus{
                  background: #549de8;
                  border-color: #409EFF;
                  color: #fff;
              }
          }
        .header-title {
          margin-left: 20px;
          color: #999999;
        }
        .currentClick{
            color:#2B2B2B!important;
        }
        .header-title:hover {
            cursor: pointer;
            text-decoration:underline;
        }
        .tit {
            line-height: 54px;
            padding-left:20px;
            border-left:1px solid #eee;
            margin-left: 20px;
        i:hover{
           text-decoration: underline;
           cursor: pointer;
         }
        .current{
          color:#2b2b2b;
          font-weight: 900;
        }
      }
        .go-back {
          padding: 10px;
        }

        .cutover-list {
          display: inline-block;
          /*float: right;*/
          width: 30px;
          text-align: center;
          font-size: 16px;
          color: $black-light;
          cursor: pointer;
          border: 1px solid $black-bg;
          background: white;
          border-radius: 3px;
        }

        .refresh:hover {
          background: $aside-bg;
          color: white;
        }

        .activeList {
          color: white;
          background: $aside-bg;
        }
      }
      .toolbar {
        padding: 10px 15px;
        height: 36px;
        line-height: 36px;
        border-bottom: 1px solid #EEEEEE;
        font-weight: 400;
        color: rgba(102, 102, 102, 1);

        .count {
          color: $blue;
        }

        .search-box {
          float: right;
          max-width: 200px;
        }
      }
    }
  }
</style>
<style lang="scss">
  #databaseContainer {

  }
</style>
